package com.fy.fyai.common.utils;

import java.net.NetworkInterface;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Enumeration;

/**
 * 雪花算法ID生成器
 * 生成24位大写字符串ID
 * @author fwq
 * @date 2025-11-02
 */
public class SnowflakeIdGenerator {

    // 工作节点ID位数
    private static final long WORKER_ID_BITS = 5L;
    // 数据中心ID位数
    private static final long DATACENTER_ID_BITS = 5L;
    // 序列号位数
    private static final long SEQUENCE_BITS = 12L;

    // 最大工作节点ID (31)
    private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
    // 最大数据中心ID (31)
    private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS);

    // 时间戳左移位数
    private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;
    // 数据中心ID左移位数
    private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    // 工作节点ID左移位数
    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;

    // 序列号掩码 (4095)
    private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);

    // 开始时间戳 (2025-01-01)
    private static final long START_EPOCH = 1735689600000L;

    private final long workerId;
    private final long datacenterId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    /**
     * 构造函数
     * @param workerId 工作节点ID (0~31)
     * @param datacenterId 数据中心ID (0~31)
     */
    public SnowflakeIdGenerator(long workerId, long datacenterId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException(String.format("Worker ID不能大于%d或小于0", MAX_WORKER_ID));
        }
        if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("Datacenter ID不能大于%d或小于0", MAX_DATACENTER_ID));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    /**
     * 生成下一个ID
     * @return 24位大写字符串ID
     */
    public synchronized String nextId() {
        long timestamp = timeGen();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("时钟向后移动，拒绝生成ID %d 毫秒", lastTimestamp - timestamp));
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & SEQUENCE_MASK;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        long id = ((timestamp - START_EPOCH) << TIMESTAMP_LEFT_SHIFT) |
                (datacenterId << DATACENTER_ID_SHIFT) |
                (workerId << WORKER_ID_SHIFT) |
                sequence;

        // 转换为24位大写十六进制字符串
        String hexString = Long.toHexString(id).toUpperCase();
        // 补齐到24位
        while (hexString.length() < 24) {
            hexString = "0" + hexString;
        }
        return hexString;
    }

    /**
     * 等待下一个毫秒
     * @param lastTimestamp 上次时间戳
     * @return 当前时间戳
     */
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    /**
     * 获取当前时间戳
     * @return 当前时间戳
     */
    private long timeGen() {
        return Instant.now().toEpochMilli();
    }

    /**
     * 获取默认实例
     * @return SnowflakeIdGenerator实例
     */
    public static SnowflakeIdGenerator getInstance() {
        return InstanceHolder.INSTANCE;
    }

    /**
     * 静态内部类持有单例实例
     */
    private static class InstanceHolder {
        private static final SnowflakeIdGenerator INSTANCE = new SnowflakeIdGenerator(getWorkerId(), getDataCenterId());

        private static long getWorkerId() {
            try {
                Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
                long macAddressHash = 0L;
                while (networkInterfaces.hasMoreElements()) {
                    NetworkInterface networkInterface = networkInterfaces.nextElement();
                    byte[] mac = networkInterface.getHardwareAddress();
                    if (mac != null) {
                        for (byte b : mac) {
                            macAddressHash = ((macAddressHash << 8) | (b & 0xff)) ^ (macAddressHash >> 4);
                        }
                        break;
                    }
                }
                return Math.abs(macAddressHash) % (MAX_WORKER_ID + 1);
            } catch (Exception e) {
                return new SecureRandom().nextInt((int) MAX_WORKER_ID + 1);
            }
        }

        private static long getDataCenterId() {
            try {
                String hostAddress = java.net.InetAddress.getLocalHost().getHostAddress();
                return Math.abs(hostAddress.hashCode()) % (MAX_DATACENTER_ID + 1);
            } catch (Exception e) {
                return new SecureRandom().nextInt((int) MAX_DATACENTER_ID + 1);
            }
        }
    }

    /**
     * 生成24位大写雪花ID的便捷方法
     * @return 24位大写字符串ID
     */
    public static String generateId() {
        return getInstance().nextId();
    }
}